#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include <signal.h>

#include <net/if.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

#include "cJSON/cJSON.h"


int main(int argc, char const *argv[])
{
    // 1，获得指定服务器的IP
    struct hostent *p;
    p = gethostbyname("ali-star-lucky.showapi.com");
    printf("服务器IP:%s\n", inet_ntoa(*(struct in_addr*)((p->h_addr_list)[0])));

    // 2，创建TCP并成功连接
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    bzero(&addr, len);
    addr.sin_family = AF_INET;
    addr.sin_addr = *(struct in_addr*)((p->h_addr_list)[0]);
    addr.sin_port = htons(80);
    if(connect(sockfd, (struct sockaddr*)&addr, len) == 0)
        printf("连接成功\n");


    // 3，按服务端规定，发送HTTP请求报文
    char *http_request();
    char *s = http_request();
    write(sockfd, s, strlen(s));


    // char *response = calloc(5, 1024);
    // read(sockfd, response, 5*1024);
    // printf("%s", response);


    // 4，接收、解析HTTP响应头部
    char *http_response = calloc(1, 1024);
    int n = 0;
    while(1)
    {
        read(sockfd, http_response+n, 1);
        n++;

        if(strstr(http_response, "\r\n\r\n"))
            break;
    }
    printf("\nHTTP响应头部:\n%s", http_response);

    // 5，接收HTTP正文
    char *json = calloc(1, 2048);
    int nread = read(sockfd, json, 2048);
    char *pp = strchr(json, '{');

    // printf("\nJSON：(%d个字节)\n%s\n", nread, pp);

    cJSON *root = cJSON_Parse(pp);
    cJSON *showapi_res_body = cJSON_GetObjectItem(root, "showapi_res_body");
    cJSON *day = cJSON_GetObjectItem(showapi_res_body, "day");
    printf("我今天的运势： %s\n", cJSON_GetObjectItem(day, "work_txt")->valuestring);
    printf("我今天的幸运数字： %s\n", cJSON_GetObjectItem(day, "lucky_num")->valuestring);

    return 0;
}

char *http_request()
{
    char *requestHead = "GET /star?star=chunv HTTP/1.1\r\n"
                        "Host: ali-star-lucky.showapi.com\r\n"
                        "Authorization: AppCode a83865167d05434f92a60aa5edb9498d\r\n\r\n";
    return requestHead;
}